Followup to r69776: cache result of extractRequestParams() because it gets called...
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2
3 /**
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
31 /**
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL
34 * queries.
35 *
36 * @ingroup API
37 */
38 abstract class ApiQueryBase extends ApiBase {
39
40 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
41
42 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
43 parent::__construct( $query->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule = $query;
45 $this->mDb = null;
46 $this->resetQueryParams();
47 }
48
49 /**
50 * Get the cache mode for the data generated by this module. Override
51 * this in the module subclass. For possible return values and other
52 * details about cache modes, see ApiMain::setCacheMode()
53 *
54 * Public caching will only be allowed if *all* the modules that supply
55 * data for a given request return a cache mode of public.
56 */
57 public function getCacheMode( $params ) {
58 return 'private';
59 }
60
61 /**
62 * Blank the internal arrays with query parameters
63 */
64 protected function resetQueryParams() {
65 $this->tables = array();
66 $this->where = array();
67 $this->fields = array();
68 $this->options = array();
69 $this->join_conds = array();
70 }
71
72 /**
73 * Add a set of tables to the internal array
74 * @param $tables mixed Table name or array of table names
75 * @param $alias mixed Table alias, or null for no alias. Cannot be
76 * used with multiple tables
77 */
78 protected function addTables( $tables, $alias = null ) {
79 if ( is_array( $tables ) ) {
80 if ( !is_null( $alias ) ) {
81 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
82 }
83 $this->tables = array_merge( $this->tables, $tables );
84 } else {
85 if ( !is_null( $alias ) ) {
86 $tables = $this->getAliasedName( $tables, $alias );
87 }
88 $this->tables[] = $tables;
89 }
90 }
91
92 /**
93 * Get the SQL for a table name with alias
94 * @param $table string Table name
95 * @param $alias string Alias
96 * @return string SQL
97 */
98 protected function getAliasedName( $table, $alias ) {
99 return $this->getDB()->tableName( $table ) . ' ' . $alias;
100 }
101
102 /**
103 * Add a set of JOIN conditions to the internal array
104 *
105 * JOIN conditions are formatted as array( tablename => array(jointype,
106 * conditions) e.g. array('page' => array('LEFT JOIN',
107 * 'page_id=rev_page')) . conditions may be a string or an
108 * addWhere()-style array
109 * @param $join_conds array JOIN conditions
110 */
111 protected function addJoinConds( $join_conds ) {
112 if ( !is_array( $join_conds ) ) {
113 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
114 }
115 $this->join_conds = array_merge( $this->join_conds, $join_conds );
116 }
117
118 /**
119 * Add a set of fields to select to the internal array
120 * @param $value mixed Field name or array of field names
121 */
122 protected function addFields( $value ) {
123 if ( is_array( $value ) ) {
124 $this->fields = array_merge( $this->fields, $value );
125 } else {
126 $this->fields[] = $value;
127 }
128 }
129
130 /**
131 * Same as addFields(), but add the fields only if a condition is met
132 * @param $value mixed See addFields()
133 * @param $condition bool If false, do nothing
134 * @return bool $condition
135 */
136 protected function addFieldsIf( $value, $condition ) {
137 if ( $condition ) {
138 $this->addFields( $value );
139 return true;
140 }
141 return false;
142 }
143
144 /**
145 * Add a set of WHERE clauses to the internal array.
146 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
147 * the latter only works if the value is a constant (i.e. not another field)
148 *
149 * If $value is an empty array, this function does nothing.
150 *
151 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
152 * to "foo=bar AND baz='3' AND bla='foo'"
153 * @param $value mixed String or array
154 */
155 protected function addWhere( $value ) {
156 if ( is_array( $value ) ) {
157 // Sanity check: don't insert empty arrays,
158 // Database::makeList() chokes on them
159 if ( count( $value ) ) {
160 $this->where = array_merge( $this->where, $value );
161 }
162 } else {
163 $this->where[] = $value;
164 }
165 }
166
167 /**
168 * Same as addWhere(), but add the WHERE clauses only if a condition is met
169 * @param $value mixed See addWhere()
170 * @param $condition boolIf false, do nothing
171 * @return bool $condition
172 */
173 protected function addWhereIf( $value, $condition ) {
174 if ( $condition ) {
175 $this->addWhere( $value );
176 return true;
177 }
178 return false;
179 }
180
181 /**
182 * Equivalent to addWhere(array($field => $value))
183 * @param $field string Field name
184 * @param $value string Value; ignored if null or empty array;
185 */
186 protected function addWhereFld( $field, $value ) {
187 // Use count() to its full documented capabilities to simultaneously
188 // test for null, empty array or empty countable object
189 if ( count( $value ) ) {
190 $this->where[$field] = $value;
191 }
192 }
193
194 /**
195 * Add a WHERE clause corresponding to a range, and an ORDER BY
196 * clause to sort in the right direction
197 * @param $field string Field name
198 * @param $dir string If 'newer', sort in ascending order, otherwise
199 * sort in descending order
200 * @param $start string Value to start the list at. If $dir == 'newer'
201 * this is the lower boundary, otherwise it's the upper boundary
202 * @param $end string Value to end the list at. If $dir == 'newer' this
203 * is the upper boundary, otherwise it's the lower boundary
204 * @param $sort bool If false, don't add an ORDER BY clause
205 */
206 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
207 $isDirNewer = ( $dir === 'newer' );
208 $after = ( $isDirNewer ? '>=' : '<=' );
209 $before = ( $isDirNewer ? '<=' : '>=' );
210 $db = $this->getDB();
211
212 if ( !is_null( $start ) ) {
213 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
214 }
215
216 if ( !is_null( $end ) ) {
217 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
218 }
219
220 if ( $sort ) {
221 $order = $field . ( $isDirNewer ? '' : ' DESC' );
222 if ( !isset( $this->options['ORDER BY'] ) ) {
223 $this->addOption( 'ORDER BY', $order );
224 } else {
225 $this->addOption( 'ORDER BY', $this->options['ORDER BY'] . ', ' . $order );
226 }
227 }
228 }
229
230 /**
231 * Add an option such as LIMIT or USE INDEX. If an option was set
232 * before, the old value will be overwritten
233 * @param $name string Option name
234 * @param $value string Option value
235 */
236 protected function addOption( $name, $value = null ) {
237 if ( is_null( $value ) ) {
238 $this->options[] = $name;
239 } else {
240 $this->options[$name] = $value;
241 }
242 }
243
244 /**
245 * Execute a SELECT query based on the values in the internal arrays
246 * @param $method string Function the query should be attributed to.
247 * You should usually use __METHOD__ here
248 * @return ResultWrapper
249 */
250 protected function select( $method ) {
251 // getDB has its own profileDBIn/Out calls
252 $db = $this->getDB();
253
254 $this->profileDBIn();
255 $res = $db->select( $this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds );
256 $this->profileDBOut();
257
258 return $res;
259 }
260
261 /**
262 * Estimate the row count for the SELECT query that would be run if we
263 * called select() right now, and check if it's acceptable.
264 * @return bool true if acceptable, false otherwise
265 */
266 protected function checkRowCount() {
267 $db = $this->getDB();
268 $this->profileDBIn();
269 $rowcount = $db->estimateRowCount( $this->tables, $this->fields, $this->where, __METHOD__, $this->options );
270 $this->profileDBOut();
271
272 global $wgAPIMaxDBRows;
273 if ( $rowcount > $wgAPIMaxDBRows ) {
274 return false;
275 }
276 return true;
277 }
278
279 /**
280 * Add information (title and namespace) about a Title object to a
281 * result array
282 * @param $arr array Result array à la ApiResult
283 * @param $title Title
284 * @param $prefix string Module prefix
285 */
286 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
287 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
288 $arr[$prefix . 'title'] = $title->getPrefixedText();
289 }
290
291 /**
292 * Override this method to request extra fields from the pageSet
293 * using $pageSet->requestField('fieldName')
294 * @param $pageSet ApiPageSet
295 */
296 public function requestExtraData( $pageSet ) {
297 }
298
299 /**
300 * Get the main Query module
301 * @return ApiQuery
302 */
303 public function getQuery() {
304 return $this->mQueryModule;
305 }
306
307 /**
308 * Add a sub-element under the page element with the given page ID
309 * @param $pageId int Page ID
310 * @param $data array Data array à la ApiResult
311 * @return bool Whether the element fit in the result
312 */
313 protected function addPageSubItems( $pageId, $data ) {
314 $result = $this->getResult();
315 $result->setIndexedTagName( $data, $this->getModulePrefix() );
316 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
317 $this->getModuleName(),
318 $data );
319 }
320
321 /**
322 * Same as addPageSubItems(), but one element of $data at a time
323 * @param $pageId int Page ID
324 * @param $item array Data array à la ApiResult
325 * @param $elemname string XML element name. If null, getModuleName()
326 * is used
327 * @return bool Whether the element fit in the result
328 */
329 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
330 if ( is_null( $elemname ) ) {
331 $elemname = $this->getModulePrefix();
332 }
333 $result = $this->getResult();
334 $fit = $result->addValue( array( 'query', 'pages', $pageId,
335 $this->getModuleName() ), null, $item );
336 if ( !$fit ) {
337 return false;
338 }
339 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
340 $this->getModuleName() ), $elemname );
341 return true;
342 }
343
344 /**
345 * Set a query-continue value
346 * @param $paramName string Parameter name
347 * @param $paramValue string Parameter value
348 */
349 protected function setContinueEnumParameter( $paramName, $paramValue ) {
350 $paramName = $this->encodeParamName( $paramName );
351 $msg = array( $paramName => $paramValue );
352 $this->getResult()->disableSizeCheck();
353 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
354 $this->getResult()->enableSizeCheck();
355 }
356
357 /**
358 * Get the Query database connection (read-only)
359 * @return Database
360 */
361 protected function getDB() {
362 if ( is_null( $this->mDb ) ) {
363 $this->mDb = $this->getQuery()->getDB();
364 }
365 return $this->mDb;
366 }
367
368 /**
369 * Selects the query database connection with the given name.
370 * See ApiQuery::getNamedDB() for more information
371 * @param $name string Name to assign to the database connection
372 * @param $db int One of the DB_* constants
373 * @param $groups array Query groups
374 * @return Database
375 */
376 public function selectNamedDB( $name, $db, $groups ) {
377 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
378 }
379
380 /**
381 * Get the PageSet object to work on
382 * @return ApiPageSet
383 */
384 protected function getPageSet() {
385 return $this->getQuery()->getPageSet();
386 }
387
388 /**
389 * Convert a title to a DB key
390 * @param $title string Page title with spaces
391 * @return string Page title with underscores
392 */
393 public function titleToKey( $title ) {
394 // Don't throw an error if we got an empty string
395 if ( trim( $title ) == '' ) {
396 return '';
397 }
398 $t = Title::newFromText( $title );
399 if ( !$t ) {
400 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
401 }
402 return $t->getPrefixedDbKey();
403 }
404
405 /**
406 * The inverse of titleToKey()
407 * @param $key string Page title with underscores
408 * @return string Page title with spaces
409 */
410 public function keyToTitle( $key ) {
411 // Don't throw an error if we got an empty string
412 if ( trim( $key ) == '' ) {
413 return '';
414 }
415 $t = Title::newFromDbKey( $key );
416 // This really shouldn't happen but we gotta check anyway
417 if ( !$t ) {
418 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
419 }
420 return $t->getPrefixedText();
421 }
422
423 /**
424 * An alternative to titleToKey() that doesn't trim trailing spaces
425 * @param $titlePart string Title part with spaces
426 * @return string Title part with underscores
427 */
428 public function titlePartToKey( $titlePart ) {
429 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
430 }
431
432 /**
433 * An alternative to keyToTitle() that doesn't trim trailing spaces
434 * @param $keyPart string Key part with spaces
435 * @return string Key part with underscores
436 */
437 public function keyPartToTitle( $keyPart ) {
438 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
439 }
440
441 public function getPossibleErrors() {
442 return array_merge( parent::getPossibleErrors(), array(
443 array( 'invalidtitle', 'title' ),
444 array( 'invalidtitle', 'key' ),
445 ) );
446 }
447
448 /**
449 * Get version string for use in the API help output
450 * @return string
451 */
452 public static function getBaseVersion() {
453 return __CLASS__ . ': $Id$';
454 }
455 }
456
457 /**
458 * @ingroup API
459 */
460 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
461
462 private $mIsGenerator;
463
464 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
465 parent::__construct( $query, $moduleName, $paramPrefix );
466 $this->mIsGenerator = false;
467 }
468
469 /**
470 * Switch this module to generator mode. By default, generator mode is
471 * switched off and the module acts like a normal query module.
472 */
473 public function setGeneratorMode() {
474 $this->mIsGenerator = true;
475 }
476
477 /**
478 * Overrides base class to prepend 'g' to every generator parameter
479 * @param $paramName string Parameter name
480 * @return string Prefixed parameter name
481 */
482 public function encodeParamName( $paramName ) {
483 if ( $this->mIsGenerator ) {
484 return 'g' . parent::encodeParamName( $paramName );
485 } else {
486 return parent::encodeParamName( $paramName );
487 }
488 }
489
490 /**
491 * Execute this module as a generator
492 * @param $resultPageSet ApiPageSet: All output should be appended to
493 * this object
494 */
495 public abstract function executeGenerator( $resultPageSet );
496 }